package com.lanhao.aot.carrierintegration.dhl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class DHLUtil {
	private static final Logger LOG = LoggerFactory.getLogger(DHLUtil.class);
	public static final String USERNAME = "28410173E-SPACE";
	public static final String PASSWORD = "541ebc9b-0d92-4825-bfe4-355eba3367b6";
	
//	public static final String AUTH_URL = "https://external.dhl.es/cimapi/api/v1/customer/authenticate";
//	public static final String SHIPMENT_URL = "https://external.dhl.es/cimapi/api/v1/customer/shipment";
	public static final String AUTH_URL = "http://47.254.176.63:9090/cimapi/api/v1/customer/authenticate";
	public static final String SHIPMENT_URL = "http://47.254.176.63:9090/cimapi/api/v1/customer/shipment";
	
	public static final String CUSTOMER = "28-410173";
	public static final String FILE_TYPE = "PDF";
	public static final String COUNTRY_CODE = "ES";
	
	public static void main(String[] args) {
		String shipment = shipment();
		LOG.info("获取标签的结果shipment={}", shipment);
	}
	
	public static String getAccessToken() {
		JSONObject request = new JSONObject();
		request.put("Username", USERNAME);
		request.put("Password", PASSWORD);
		HttpResponse resp = HttpRequest.post(AUTH_URL).body(request.toJSONString()).execute();
		if (resp.isOk()) {
			return resp.body();
		}
		return "";
	}
	
	public static String shipment() {
 		String token = getAccessToken();
		if(StringUtils.isBlank(token)) {
			LOG.info("token获取失败，取消请求");
			return "";
		}
		token = removeDoubleQuotes(token);
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Authorization", "Bearer " + token);
		headerMap.put("Content-Type", "application/json");
		
		JSONObject requestBody = new JSONObject();
		requestBody.put("Customer", CUSTOMER);
		JSONObject receiver = new JSONObject();
		receiver.put("Name", "DHL Parcel Madrid");
		receiver.put("Address", "Río Almanzora, s/n");
		receiver.put("City", "Getafe");
		receiver.put("PostalCode", "28906");
		receiver.put("Country", COUNTRY_CODE);
//		receiver.put("Phone", "34914237100");
//		receiver.put("Email", "receiver@dhl.com");
		// TODO 补充收件人信息
		requestBody.put("Receiver", receiver);

		JSONObject sender = new JSONObject();
		sender.put("Name", "DHL Parcel Barcelona");
		sender.put("Address", "Les Minetes, 3-2");
		sender.put("City", "Sta Perpetua Mogoda");
		sender.put("PostalCode", "08130");
		sender.put("Country", COUNTRY_CODE);
//		sender.put("Phone", "+34935656564");
//		sender.put("Email", "");
		// 补充发件人信息
		requestBody.put("Sender", sender);

		requestBody.put("Reference",  UUID.randomUUID().toString().replaceAll("-", ""));
		requestBody.put("Quantity", 1);
		requestBody.put("Weight", 1);
//		requestBody.put("WeightVolume", 0);

//		requestBody.put("CODAmount", 0);
//		requestBody.put("CODExpenses", "P");
//		requestBody.put("CODCurrency", "EUR");
//		requestBody.put("InsuranceAmount", 0);
//		requestBody.put("InsuranceExpenses", "P");
//		requestBody.put("InsuranceCurrency", "EUR");
//		requestBody.put("DeliveryNote", "");
//		requestBody.put("Remarks1", "");
//		requestBody.put("Remarks2", "");
		requestBody.put("Incoterms", "CPT");
//		requestBody.put("ContactName", "");
//		requestBody.put("GoodsDescription", "");
//		requestBody.put("CustomsValue", 0);
//		requestBody.put("CustomsCurrency", "");
		requestBody.put("Format", FILE_TYPE);
		requestBody.put("Product", "R2C");
		HttpResponse resp = HttpRequest.post(SHIPMENT_URL).addHeaders(headerMap).body(requestBody.toJSONString()).execute();
		String respResult = resp.body();
		LOG.info("resp result={}", respResult);
		if (StringUtils.isBlank(respResult)) {
			LOG.info("调用获取面单接口返回信息为空");
			return "";
		}
		try {
			FileUtils.write(new File("D:/DHL_Resp.txt"), respResult, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject resultObject = JSON.parseObject(respResult);
		if (resp.isOk()) {
			String tracking = resultObject.getString("Tracking");
			String lp = resultObject.getString("LP");
			String label = resultObject.getString("Label");
			Base64.decodeToFile(label, new File("D:/" + tracking + ".pdf"));
			return tracking + "_" + lp;
		} else {
			String message = resultObject.getString("Message");
			LOG.info("获取标签失败，返回信息Message={}", message);
		}
		return "";
	}
	
	public static String removeDoubleQuotes(String result) {
        //去掉" "号
        return result.replace("\"", ""); 
    }
}
